<template>
  <section class="organizationBody">
    <div class="topHandleCon">
      <el-row
        v-if="activeNav == '组织设置'"
        :gutter="1"
      >
        <el-col
          :span="1"
          class="topHandleConLeft"
          style="margin-right: 20px"
        >
          <el-row>
            <el-col :span="24">
              <el-radio-group
                v-model="switchList"
                style="display: flex; flex-direction: column"
                @change="handleSwitchListChange"
              >
                <el-radio
                  :label="true"
                  border
                  size="small"
                  fill="#fff"
                  style="display: inline-block; margin: 0; padding: 0; height: 25px"
                >列表</el-radio>
                <el-radio
                  :label="false"
                  border
                  size="small"
                  fill="#fff"
                  style="display: inline-block; margin: 0; padding: 0; height: 25px"
                >树形</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
        </el-col>
        <el-col
          :span="4"
          class="topHandleConLeft"
        >
          <el-card :body-style="{ padding: 0 }">
            <el-row :gutter="2">
              <el-col :span="8">
                <div class="time-title">行业属性</div>
              </el-col>
              <el-col :span="16">
                <el-select
                  v-model="getDataParams.tradeType"
                  clearable
                  class="company-sel"
                  size="small"
                  @change="getOrgList({ current: 1 })"
                >
                  <el-option
                    v-for="item in tradeTypeList"
                    :key="item.encode"
                    :label="item.name"
                    :value="item.encode"
                  />
                </el-select>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
        <el-col
          :span="5"
          class="topHandleConLeft"
        >
          <el-card :body-style="{ padding: 0 }">
            <el-row :gutter="2">
              <el-col :span="10">
                <div class="time-title">所属组织单元</div>
              </el-col>
              <el-col :span="14">
                <!-- getOrgTypeList -->
                <el-select
                  v-model="getDataParams.orgGroupId"
                  :remote-method="getOrgTypeList"
                  filterable
                  remote
                  class="company-sel"
                  size="small"
                  clearable
                  placeholder="请输入关键词搜索"
                  @change="getOrgList({ current: 1 })"
                >
                  <el-option
                    v-for="item in normalUnitTableData"
                    :key="item.phid"
                    :label="item.name"
                    :value="item.phid"
                  />
                </el-select>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
        <el-col
          :span="13"
          class="greenBtnW"
        >
          <el-row
            :gutter="5"
            class="txtR"
          >
            <el-col
              :offset="switchList ? 0 : 13"
              :span="10"
              class="txtR"
            >
              <search-input
                v-model="getDataParams.nameOrEncode"
                :show-btn="false"
                placeholder="组织编码/名称"
                @btnClick="getOrgList({ current: 1 })"
              />
            </el-col>
            <template v-if="switchList">
              <el-col
                :span="4"
                class="txtR"
              >
                <el-popover
                  trigger="hover"
                  width="200"
                  placement="bottom"
                >
                  <ul
                    class="moreBtn"
                    style="margin-bottom:10px;"
                  >
                    <li
                      v-for="item in codeLengthSettingList"
                      :key="item.value"
                    >
                      <span style="width:60px;">{{ item.name }}</span>
                      <el-input-number
                        v-model="item.level"
                        :controls="false"
                        :min="0"
                        style="width:110px"
                        clearable
                      />
                    </li>
                  </ul>
                  <!-- <div class="greenBtn">取消</div> -->
                  <div
                    class="greenBtn"
                    style="margin-left: 50px"
                    @click="setCodeLengthSettingList"
                  >保存</div>
                  <p style="color:red;margin-top:10px;font-weight:bold;">注：请根据实际情况设置组织代码宽度，组织代码宽度一旦设置将不可修改，请谨慎操作！</p>
                  <div
                    slot="reference"
                    class="greenBtn"
                  >代码宽度设置</div>
                </el-popover>
              </el-col>
              <el-col
                :span="2"
                class="txtR"
              >
                <div>
                  <div
                    class="greenBtn"
                    @click="openAddOrganization(0)"
                  >新增</div>
                </div>
              </el-col>
              <el-col
                :span="2"
                class="txtR"
              >
                <div>
                  <div
                    class="greenBtn"
                    @click="openAddOrganization(1)"
                  >修改</div>
                </div>
              </el-col>
              <el-col
                :span="2"
                class="txtR"
              >
                <div>
                  <el-popover
                    trigger="hover"
                    width="90"
                    placement="bottom"
                  >
                    <ul class="moreBtn">
                      <li>
                        <span
                          class="greenBtn"
                          @click="openDeleteOrganization"
                        >删除</span>
                      </li>
                      <li @click="handleUpload">
                        <span class="greenBtn">导入</span>
                      </li>
                      <li @click="handleExport">
                        <span class="greenBtn">导出</span>
                      </li>
                      <li>
                        <span class="greenBtn" @click="handlePrint">打印</span>
                      </li>
                    </ul>
                    <div
                      slot="reference"
                      class="greenBtn"
                    >
                      更多
                      <i class="el-icon-caret-bottom" />
                    </div>
                  </el-popover>
                </div>
              </el-col>
              <el-col
                :span="3"
                class="txtR"
              >
                <div>
                  <div
                    class="greenBtn"
                    @click="openCreateUnit"
                  >创建单元</div>
                </div>
              </el-col>
            </template>
            <el-col
              :span="1"
              class="txtR"
            >
              <div class="fresh">
                <div @click="refresh">
                  <i class="el-icon-refresh" />
                </div>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row
        v-if="activeNav == '组织单元设置'"
        :gutter="1"
      >
        <el-col
          :span="11"
          class="topHandleConLeft"
          style="height:36px;"
        />
        <el-col
          :span="13"
          class="greenBtnW"
        >
          <el-row
            :gutter="5"
            class="txtR"
          >
            <el-col
              :offset="11"
              :span="10"
              class="txtR"
            >
              <search-input
                v-model="getUnitDataParams.nameOrEncode"
                :show-btn="false"
                placeholder="请输入组织单元名称搜索"
                @btnClick="handleSearchOrgGroup"
              />
            </el-col>
            <el-col
              :span="2"
              class="txtR"
            >
              <div>
                <div
                  class="greenBtn"
                  @click="openAddOrgUnit(0, '')"
                >新增</div>
              </div>
            </el-col>
            <el-col
              :span="1"
              class="txtR"
            >
              <div class="fresh">
                <div @click="refresh">
                  <i class="el-icon-refresh" />
                </div>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>
    <div class="organizationBody-main">
      <div style="height:calc(100% - 33px);">
        <el-row style="height:100%">
          <el-col :span="4">
            <ul class="organizationBody-nav">
              <li
                v-for="(item, index) in navs"
                :key="index"
                :class="{ active: activeNav == item }"
                @click="activeNav = item"
              >{{ item }}</li>
            </ul>
          </el-col>
          <el-col
            :style="'height: 95%;padding: 10px 10px 45px; position: relative;box-shadow: #05050638 0px 0px 3px 0px;top: 2px;'+(activeNav=='组织设置'&&switchList?'padding-bottom:0;':'')"
            :span="20"
          >
            <!-- 组织设置 -->
            <div
              v-if="activeNav == '组织设置'"
              style="height:100%"
            >
              <div
                v-if="switchList"
                style="height:100%"
              >
                <el-table
                  ref="multipleTable"
                  :data="tableData"
                  height="100%"
                  tooltip-effect="dark"
                  border
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                  @row-dblclick="orgRowDblclick"
                >
                  <el-table-column
                    width="80"
                    header-align="center"
                    align="center"
                  >
                    <template
                      slot="header"
                      slot-scope="scope"
                    >
                      <span v-if="false">{{ scope.row }}</span>
                      <el-checkbox
                        v-model="checkedAll"
                        @change="checkAll"
                      >序号</el-checkbox>
                    </template>
                    <template slot-scope="scope">
                      <el-checkbox
                        v-model="scope.row.checked"
                        @change="checkOne"
                      >{{ scope.$index + 1 }}</el-checkbox>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-for="(item, index) in organizationColumn"
                    :key="index"
                    :prop="item.prop"
                    :label="item.label"
                    :width="item.width || ''"
                    header-align="center"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <template v-if="scope.column.property == 'tradeType'">
                        {{ scope.row.tradeType != null ?tradeTypeList.find(i => i.encode ==scope.row.tradeType ).name:'' }}
                      </template>
                      <template v-else-if="scope.column.property == 'type'">
                        {{ scope.row.type?typeList.find(i => i.encode ==scope.row.type).name:'' }}
                      </template>
                      <template v-else>
                        {{ scope.row[scope.column.property] }}
                      </template>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="pageArea">
                  <el-pagination
                    :current-page="getDataParams.current"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="getDataParams.size"
                    :total="getDataParams.total"
                    layout="total,sizes,prev,pager,next,jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                  />
                </div>
              </div>
              <div
                v-else
                style="height:100%"
              >
                <LazyTree />
              </div>
            </div>
            <!-- 组织单元设置 -->
            <div
              v-else-if="activeNav == '组织单元设置'"
              :key="orgGroupKey"
              style="height:100%"
            >
              <el-table
                v-if="activeNav == '组织单元设置'"
                :data="unitTableData"
                :load="getOrgGroupLevelList"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                height="100%"
                tooltip-effect="dark"
                border
                style="width: 100%"
                row-key="phid"
                lazy
                @row-dblclick="unitRowDblclick"
              >
                <el-table-column
                  v-for="(item, index) in organizationUnitColumn"
                  :key="index"
                  :prop="item.prop"
                  :label="item.label"
                  :width="item.width || ''"
                  :header-align="item.headerAlign || 'center'"
                  :align="item.align || 'center'"
                >
                  <template slot-scope="scope">
                    <template v-if="scope.column.property == 'orgCount'">
                      <span
                        class="link"
                        @click="scope.row.children.length?openEditOrganizationUnit(scope.row):openAddOrgUnit(3,scope.row.phid,scope.row)"
                      >{{ scope.row.orgNumber || '添加' }}</span>
                    </template>
                    <template v-else-if="scope.column.property == 'handle'">
                      <el-popover
                        trigger="hover"
                        width="150"
                        placement="right"
                      >
                        <ul class="unitEdit">
                          <li @click="openAddOrgUnit(0, scope.row.parentid)">
                            <span>新增同级</span>
                          </li>
                          <li @click="openAddOrgUnit(0, scope.row.phid)">
                            <span>新增下级</span>
                          </li>
                          <li
                            @click="
                              openAddOrgUnit(1, scope.row.phid, scope.row)
                            "
                          >
                            <span>修改</span>
                          </li>
                          <li @click="opendeleteOrganizationUnit(scope.row)">
                            <span>删除</span>
                          </li>
                        </ul>
                        <span
                          slot="reference"
                          class="link"
                        >编辑</span>
                      </el-popover>
                    </template>
                    <template v-else>
                      {{
                        scope.row[scope.column.property]
                      }}
                    </template>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- 组织新增/详情 -->
    <el-dialog
      v-if="addOrganizationShow"
      :visible.sync="addOrganizationShow"
      :close-on-click-modal="false"
      :title="
        !addOrganizationType
          ? '新增组织'
          : addOrganizationType == 1
            ? '修改组织'
            : '查看组织'
      "
      append-to-body
      custom-class="addOrganizationClass"
    >
      <Add-Organization
        v-if="addOrganizationShow"
        :add-organization-show.sync="addOrganizationShow"
        :add-organization-type="addOrganizationType"
        :add-organization-parent-id="addOrganizationParentId"
        :data="addOrganizationData"
      />
    </el-dialog>
    <!-- 删除组织 -->
    <el-dialog
      v-if="deleteOrganizationShow"
      :visible.sync="deleteOrganizationShow"
      :close-on-click-modal="false"
      custom-class="deleteOrganizationClass"
      append-to-body
      title="提示"
    >
      <div style="text-align: justify;padding: 0 15px;">该组织或其下级组织已存在业务数据，需要清除组织业务数据才可删除组织，是否直接清除组织数据或备份组织数据后清除？</div>
      <el-radio-group v-model="deleteOrganizationSelect">
        <el-radio :label="0">直接清除组织业务数据</el-radio>
        <span class="radio-label">组织业务数据清除后自动删除组织</span>
        <el-radio :label="1">备份组织数据再清除</el-radio>
        <span class="radio-label">备份组织数据后自动删除组织</span>
      </el-radio-group>
      <div style="text-align:center;margin:10px auto;">
        <span
          class="greenBtn"
          @click="deleteOrganizationShow = false"
        >取消</span>
        <span
          class="greenBtn"
          @click="deleteOrgAfterSelect"
        >确定</span>
      </div>
    </el-dialog>
    <!-- 组织tab-新增组织单元-不需要组织树 -->
    <el-dialog
      v-if="createUnitShow"
      :visible.sync="createUnitShow"
      :close-on-click-modal="false"
      custom-class="createUnitClass"
      append-to-body
      title="创建单元"
    >
      <template v-if="createUnitShow">
        <div class="createUnitList">
          <span>组织单元名称：</span>
          <el-input
            v-model="createUnitName"
            placeholder="必填"
            clearable
          />
        </div>
        <div class="createUnitList">
          <span>备注：</span>
          <el-input
            v-model="createUnitRemarks"
            type="textarea"
            placeholder="请输入内容"
            maxlength="30"
            show-word-limit
          />
        </div>
        <div style="text-align:center;">
          <span
            class="greenBtn"
            @click="createUnitShow = false"
          >取消</span>
          <span
            class="greenBtn"
            @click="addOrgType"
          >保存</span>
        </div>
      </template>
    </el-dialog>
    <!-- 组织单元详情 -->
    <el-dialog
      v-if="addOrgUnitObj.addOrgUnitShow"
      :visible.sync="addOrgUnitObj.addOrgUnitShow"
      :close-on-click-modal="false"
      :title="
        addOrgUnitObj.addOrgUnitType == 0
          ? '新增组织单元'
          : addOrgUnitObj.addOrgUnitType == 1 || addOrgUnitObj.addOrgUnitType == 3
            ? '修改组织单元'
            : '查看组织单元'
      "
      append-to-body
      custom-class="addOrganizationClass"
    >
      <add-org-unit
        v-if="addOrgUnitObj.addOrgUnitShow"
        :add-org-unit-show.sync="addOrgUnitObj.addOrgUnitShow"
        :add-org-unit-type="addOrgUnitObj.addOrgUnitType"
        :add-org-unit-obj="addOrgUnitObj"
        @refresh="refresh"
      />
    </el-dialog>
    <!-- 删除组织单元 -->
    <el-dialog
      v-if="deleteOrganizationUnitShow"
      :visible.sync="deleteOrganizationUnitShow"
      :close-on-click-modal="false"
      custom-class="deleteOrganizationClass"
      append-to-body
      title="提示"
    >
      <div style="text-align: justify;padding: 0 15px;">单元内组织已存在业务数据，需要清除组织业务数据才可删除组织单元，是否直接清除组织数据或备份组织数据后清除？</div>
      <el-radio-group v-model="deleteOrganizationUnitSelect">
        <el-radio :label="0">直接清除组织业务数据</el-radio>
        <span class="radio-label">组织业务数据清除后自动删除组织单元</span>
        <el-radio :label="1">备份组织数据再清除</el-radio>
        <span class="radio-label">备份组织数据后自动删除组织单元</span>
      </el-radio-group>
      <div style="text-align:center;margin:10px auto;">
        <span
          class="greenBtn"
          @click="deleteOrganizationUnitShow = false"
        >取消</span>
        <span
          class="greenBtn"
          @click="deleteOrgUnitAfterSelect"
        >确定</span>
      </div>
    </el-dialog>
    <!-- 组织单元-编辑组织 -->
    <el-dialog
      v-if="editOrganizationUnitShow"
      :visible.sync="editOrganizationUnitShow"
      :close-on-click-modal="false"
      custom-class="editOrganizationClass"
      append-to-body
      title="组织查询"
    >
      <edit-org-tree
        v-if="editOrganizationUnitShow"
        ref="editOrgTree"
        :detail="editOrganizationUnitData"
      />
      <div style="text-align:right;margin:10px auto;">
        <span
          class="greenBtn"
          @click="editOrganizationUnitShow = false"
        >取消</span>
        <span
          class="greenBtn"
          @click="fastSave"
        >保存</span>
      </div>
    </el-dialog>
    <OrgPrint ref="orgPrint" :print-data="printData" />
  </section>
</template>

<script>
import SearchInput from '../../components/searchInput/index'
import AddOrganization from './addOrganization'
import addOrgUnit from './addOrgUnit'
import editOrgTree from './editOrgTree'
import LazyTree from './lazy-tree'
import OrgPrint from './org-print'
import ExcelUpload from '@/components/ExcelUpload'
import {
  getOrgList,
  getAllOrgGroupList,
  addOrgGroup,
  deleteOrg,
  deleteOrgGroup,
  findOneOrg,
  getOrgTreeList,
  listOrgGroupByParentId,
  orgExport,
  orgImportUrl,
  getEnCodeSet,
  editEnCodeSet,
  orgExportTemplate
} from '@/api/organization/'
import { mapState } from 'vuex'
import { getToken } from '@/utils/auth'
import printJS from 'print-js'

export default {
  name: 'Organization',
  components: {
    SearchInput,
    AddOrganization,
    addOrgUnit,
    editOrgTree,
    LazyTree,
    OrgPrint
  },
  data() {
    return {
      orgImportUrl,
      headers: {
        token: getToken(),
        currentOrgId: this.$store.state.user.orgId
      },
      printData: [],
      uuid: {}, // 新增重复提交
      addOrganizationData: null,
      editOrganizationUnitData: null,
      editOrganizationUnitShow: false,
      deleteOrganizationUnitShow: false,
      deleteOrganizationUnitSelect: '',
      deleteOrganizationUnitItem: null,
      orgGroupKey: Math.random(),
      addOrgUnitObj: {
        addOrgUnitShow: false,
        addOrgUnitType: 0, // 0|新增组织单元 1|修改组织单元 2|查看组织单元
        parentId: '',
        orgList: [],
        defaultList: [],
        detail: null
      },
      orgDefaultProps: {
        children: 'children',
        label: 'name'
      },
      createUnitShow: false,
      addOrganizationShow: false,
      addOrganizationType: 0, // 0|新增组织 1|修改组织 2|查看组织
      addOrganizationParentId: '',
      deleteOrganizationShow: false,
      deleteOrganizationSelect: '',
      switchList: true,
      type: '',
      allCompany: [],
      searchVal: '',
      phids: [],
      codeLengthSettingList: [
        {
          name: '一级组织',
          level: undefined
        },
        {
          name: '二级组织',
          level: undefined
        },
        {
          name: '三级组织',
          level: undefined
        },
        {
          name: '四级组织',
          level: undefined
        },
        {
          name: '五级组织',
          level: undefined
        },
        {
          name: '六级组织',
          level: undefined
        },
        {
          name: '七级组织',
          level: undefined
        }
      ],
      tableData: [],
      activeNav: '',
      normalTreeData: [],
      treeData: [],
      organizationColumn: [
        {
          label: '组织编码',
          prop: 'encode',
          width: 150
        },
        {
          label: '组织名称',
          prop: 'name',
          width: 120
        },
        {
          label: '统一社会信用社代码',
          prop: 'enterpriseCode',
          minWidth: 240
        },
        {
          label: '行业属性',
          prop: 'tradeType',
          width: 120
        },
        {
          label: '组织类型',
          prop: 'type',
          width: 120
        },
        {
          label: '所属组织单元',
          prop: 'orgGroupName',
          minWidth: 240
        },
        {
          label: '单位负责人',
          prop: 'manager',
          width: 120
        },
        {
          label: '联系电话',
          prop: 'managerMobile',
          width: 120
        }
      ],
      unitTableData: [],
      normalUnitTableData: [],
      organizationUnitColumn: [
        {
          label: '组织单元名称',
          prop: 'name',
          align: 'left'
        },
        {
          label: '创建人',
          prop: 'userName'
        },
        {
          label: '创建时间',
          prop: 'ngInsertDt',
          width: 120
        },
        {
          label: '包含组织',
          prop: 'orgCount',
          width: 120
        },
        {
          label: '备注',
          prop: 'description'
        },
        {
          label: '操作',
          prop: 'handle',
          width: 240
        }
      ],
      multipleSelection: [],
      getDataParams: {
        total: 0,
        nameOrEncode: '', // (string, optional): 组织编码/名称 ,
        order: '', // (string, optional): 排序方式 asc/desc ,
        orgGroupId: '', // (integer, optional): 所属组织单元id ,
        current: 1, // (integer, optional): 页号 ,
        size: 10, // (integer, optional): 页面大小 ,
        sort: '', // (string, optional): 排序字段 ,
        tradeType: '' // (string, optional): 行业属性
      },
      getUnitDataParams: {
        nameOrEncode: '', // (string, optional): 组织编码/名称 ,
        order: '', // (string, optional): 排序方式 asc/desc ,
        current: 1, // (integer, optional): 页号 ,
        size: 10, // (integer, optional): 页面大小 ,
        sort: '', // (string, optional): 排序字段 ,
        tradeType: '' // (string, optional): 行业属性
      },
      checkedAll: false,
      checkedList: false,
      createUnitName: '',
      createUnitRemarks: '',
      tradeTypeList: [
        {
          encode: 0,
          name: '行政单位'
        },
        {
          encode: 1,
          name: '事业单位'
        },
        {
          encode: 2,
          name: '村集体经济组织'
        },
        {
          encode: 3,
          name: '其他'
        }
      ],
      typeList: [
        {
          encode: '0',
          name: '常用组织'
        },
        {
          encode: '1',
          name: '总预算组织'
        },
        {
          encode: '2',
          name: '支付中心组织'
        },
        {
          encode: '3',
          name: '统管组织'
        }
      ]
    }
  },
  computed: {
    ...mapState({
      orgId: state => state.user.orgId,
      userid: state => state.user.userid,
      usertype: state => state.user.usertype,
      role: state => state.user.role
    }),
    navs() {
      return this.role === 4
        ? ['组织单元设置']
        : this.role === 5
          ? ['组织设置']
          : ['组织设置', '组织单元设置']
    }
  },
  watch: {
    createUnitShow(val) {
      if (!val) {
        this.createUnitName = ''
        this.createUnitRemarks = ''
      }
    },
    deleteOrganizationShow(val) {
      if (!val) {
        this.deleteOrganizationSelect = ''
      }
    },
    deleteOrganizationUnitShow(val) {
      if (!val) {
        this.deleteOrganizationUnitSelect = ''
      }
    }
  },
  created() {
    this.activeNav = this.role === 4 ? '组织单元设置' : '组织设置'
    this.getOrgList()
    this.getCodeLengthSettingList()
    this.getOrgGroupByParentId(0).then(res => {
      this.unitTableData = res
    })
  },
  provide() {
    return {
      getOrgList: this.getOrgList,
      getOrgTypeList: this.getOrgTypeList,
      getOrgTreeList: this.getOrgTreeList,
      uuid: this.uuid
    }
  },
  methods: {
    handleUpload() {
      this.$popup(ExcelUpload, {
        action: orgImportUrl,
        downloadTemplate: orgExportTemplate
        // downErrorExcel: exportErrorOrgList
      }).then(res => {
        this.$nextTick(() => {
          this.fresh()
        })
      }).catch(err => {
        console.log('err', err)
      })
    },
    handleImportSuccess(res) {
      this.$msgBox.show('导入成功，请稍后查看')
      this.refresh()
    },
    handleImportError(err) {
      this.$msgBox.error(err.message || '导入成功')
    },
    handlePrint() {
      getOrgList({
        ...this.getDataParams,
        current: 1,
        size: 99999
      }).then((res) => {
        console.log('handlePrint', res)
        this.printData = res.data.records

        this.$nextTick(() => {
          printJS({
            printable: 'printJS-form',
            type: 'html',
            scanStyles: true,
            css: ['https://cdn.bootcss.com/element-ui/2.12.0/theme-chalk/index.css']
          })
        })
      })
    },
    checkAll(val, e) {
      this.tableData.forEach(item => {
        item.checked = val
      })
    },
    checkOne(val) {
      this.checkedAll =
        this.tableData.length && this.tableData.every(item => item.checked)
    },
    getOrgGroupLevelList(tree, treeNode, resolve) {
      this.getOrgGroupByParentId(tree.phid).then(res => {
        resolve(res)
      })
    },
    // 获取组织编码宽度
    getCodeLengthSettingList() {
      getEnCodeSet()
        .then(res => {
          console.log(res)
          if (res.status) {
            const codeArr = res.data ? res.data.value.split('-') : []
            this.codeLengthSettingList.forEach((item, index) => {
              item.level = codeArr[index] || null
            })
          } else {
            this.$msgBox.error(res.message)
          }
        })
        .catch(err => {
          console.log(err)
          this.$msgBox.error('获取组织代码宽度失败！')
        })
    },
    // 设置组织编码宽度
    setCodeLengthSettingList() {
      console.log(this.codeLengthSettingList)
      const code = this.codeLengthSettingList
        .map(v => v.level)
        .join('-')

      editEnCodeSet(code)
        .then(res => {
          console.log(res)
          if (res.status) {
            // this.codeLengthSettingList.forEach((item, index) => {
            //   item['level'] = res.data
            // })
          } else {
            this.$msgBox.error(res.message)
            this.getCodeLengthSettingList()
          }
        })
        .catch(err => {
          console.log(err)
          this.$msgBox.error('设置组织代码宽度失败！')
          this.getCodeLengthSettingList()
        })
    },
    openEditOrganizationUnit(item) {
      console.log(item)
      this.editOrganizationUnitData = item
      this.editOrganizationUnitShow = true
    },
    // 组织单元tab-组织单元详情
    async openAddOrgUnit(val, phid, row) {
      // 0|新增组织单元 1|修改组织单元 2|查看组织单元
      // 新增和修改需要拉取所有组织列表
      // 新增时需要parentid
      // 修改时需要默认选择phids
      // 查看时选中所有组织,组织树结构和新增修改不一样，具体在组件中修改
      // 此处所有列表都无嵌套
      // try {
      //   var res = await getAllOrgList({})
      //   if (res.status) {
      //     this.addOrgUnitObj.orgList = res.data
      //   } else {
      //     this.$msgBox.error(res.message)
      //     return
      //   }
      // } catch (error) {
      //   console.log(error)
      //   this.$msgBox.error('获取组织列表失败！')
      //   return
      // }
      if (val === 0) {
        console.log('addOrgUnitObj.parentId', phid)
        this.addOrgUnitObj.parentId = phid
      } else if (val === 1) {
        this.addOrgUnitObj.detail = row
        this.addOrgUnitObj.defaultList = row.children.length ? row.children.map(i => i.phid) : []
      } else if (val === 2) {
        this.addOrgUnitObj.detail = row
        this.addOrgUnitObj.defaultList = row.children.length ? row.children.map(i => i.phid) : []
      } else if (val === 3) {
        this.addOrgUnitObj.detail = row
        this.addOrgUnitObj.defaultList = row.children.length ? row.children.map(i => i.phid) : []
      }
      console.log('open addOrgUnit')
      this.addOrgUnitObj.addOrgUnitType = val
      this.addOrgUnitObj.addOrgUnitShow = true
    },
    handleEdit(index, row, column) {
      console.log(index, row, column)
    },
    handleSearchOrgGroup() {
      this.getOrgGroupByParentId(0, this.getUnitDataParams.nameOrEncode).then(res => {
        this.unitTableData = res
      })
    },
    addOrgType() {
      addOrgGroup({
        description: this.createUnitRemarks,
        levels: 0,
        name: this.createUnitName,
        orgIds: this.phids,
        parentid: ''
      })
        .then(res => {
          if (res.status) {
            this.$msgBox.show('新增组织单元成功！')
            this.createUnitShow = false
            this.getOrgList()
            // this.getOrgTypeList()
          } else {
            this.$msgBox.error(res.message || '新增组织单元失败！')
          }
        })
        .catch(err => {
          console.log(err)
          this.$msgBox.error('新增组织单元失败！')
        })
    },
    // 组织tab页-新增组织单元
    openCreateUnit() {
      var phids
      if (this.switchList) {
        var arr = this.tableData.filter(i => i.checked)
        if (!arr.length) {
          this.$msgBox.error('请至少选择一条数据！')
          return
        } else if (arr.some(i => i.orgTypeId)) {
          this.$msgBox.error(
            '所选组织已有组织单元，请重新选择组织!'
          )
          return
        }
        phids = this.tableData.filter(i => i.checked).map(i => i.phid)
      } else {
        if (this.$refs.orgTree) {
          phids = this.$refs.orgTree.getCheckedKeys()
          if (!phids.length) {
            this.$msgBox.error('请至少选择一条数据！')
            return
          } else if (
            this.normalTreeData.filter(phids.includes).some(i => i.orgTypeId)
          ) {
            this.$msgBox.error(
              '所选组织已有组织单元，请重新选择组织!'
            )
            return
          }
        }
      }
      this.phids = phids
      this.createUnitShow = true
    },
    // 组织树渲染方式
    treeRender(h, { node, data, store }) {
      return <span>{data.encode + data.name}</span>
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取组织列表
    getOrgList(params) {
      const _param = {
        ...this.getDataParams,
        ...params
      }
      // 获取表格组织
      return getOrgList(_param)
        .then(res => {
          if (res.status) {
            const { records = [], total } = res.data
            records.forEach(item => {
              item.checked = false
            })
            this.checkedAll = false
            this.tableData = records
            this.getDataParams.total = total
            return res
          } else {
            this.checkedAll = false
            this.$msgBox.error(res.message)
          }
        })
        .catch(err => {
          this.checkedAll = false
          console.log(err)
          this.$msgBox.error('获取组织列表失败！')
        })
    },
    handleSwitchListChange(val) {
      !val && this.getOrgTreeList()
    },
    // 获取组织树
    getOrgTreeList() {
      getOrgTreeList().then(res => {
        if (res.status) {
          this.treeData = res.data
          console.log('为什么getOrgTreeList', res.data)
        } else {
          this.$msgBox.error(res.message)
        }
      }).catch(err => {
        console.log(err)
        this.$msgBox.error('获取组织列表失败！')
      })
    },
    // 获取组织单元列表
    getOrgTypeList(query) {
      if (query !== '') {
        getAllOrgGroupList({
          nameOrId: query
        }).then(res => {
          if (res.status) {
            this.normalUnitTableData = res.data
          } else {
            this.$msgBox.error(res.message)
          }
        }).catch(err => {
          console.log(err)
          this.$msgBox.error('获取组织单元列表失败！')
        })
      }
    },
    getOrgGroupByParentId(parentId, nameOrId = '') {
      return listOrgGroupByParentId({ parentId, nameOrId }).then(res => {
        const data = res.data || []
        return data.map(v => ({
          ...v,
          hasChildren: true,
          children: []
        }))
      })
    },
    handleSizeChange(val) {
      // console.log('handleSizeChange', val)
      this.getDataParams.size = val
      this.getOrgList()
    },
    handleCurrentChange(val) {
      // console.log('handleCurrentChange', val)
      this.getDataParams.current = val
      this.getOrgList()
    },
    async getOrgInfo(phid) {
      // findOneOrg
      await findOneOrg({ id: phid })
        .then(res => {
          console.log(res)
          if (res.status) {
            this.addOrganizationData = res.data
          } else {
            this.$msgBox.error(res.message)
          }
        })
        .catch(err => {
          console.log(err)
          this.$msgBox.error('获取组织详情失败！')
        })
    },
    orgRowDblclick(row, column, event) {
      this.openAddOrganization(2, row.phid)
    },
    unitRowDblclick(row, column, event) {
      this.openAddOrgUnit(2, '', row)
    },
    async openAddOrganization(val, phid) {
      const checkList = this.tableData.filter(item => item.checked)
      if (!val) {
        this.uuid.id = new Date().getTime()
        if (checkList.length) {
          this.addOrganizationParentId = checkList[0].phid
        }
        console.log('打开新增')
      } else if (val === 1) {
        if (checkList.length !== 1) {
          this.$msgBox.error('请选择一条数据进行修改！')
          return
        } else {
          await this.getOrgInfo(checkList[0].phid)
        }
      } else {
        await this.getOrgInfo(phid)
      }
      console.log('open')
      this.addOrganizationType = val
      this.addOrganizationShow = true
    },
    // 删除组织
    deleteOrg(params) {
      deleteOrg(params)
        .then(res => {
          console.log(res)
          if (res.status) {
            this.$msgBox.show('组织删除成功！')
            this.deleteOrganizationSelect = ''
            this.deleteOrganizationShow = false
            this.getOrgList()
            // this.getOrgTypeList()
          } else {
            this.$msgBox.error(res.message)
          }
        })
        .catch(err => {
          console.log(err)
          this.$msgBox.error('组织删除失败！')
        })
    },
    openDeleteOrganization() {
      var ids = this.tableData.filter(i => i.checked).map(i => i.phid.toString())
      if (!ids.length) {
        this.$msgBox.error('请至少选择一条数据！')
        return
      }
      this.$confirm('删除后相关数据将清空，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteOrg({
          backup: false,
          ids
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    deleteOrgAfterSelect() {
      if (this.deleteOrganizationSelect === '') {
        this.$msgBox.error('请选择删除方式！')
        return
      }
      this.deleteOrg({
        backup: !!this.deleteOrganizationSelect,
        ids: this.tableData.filter(i => i.checked).map(i => i.phid.toString())
      })
    },
    // 删除组织单元
    deleteOrgGroup(params) {
      return deleteOrgGroup(params)
        .then(res => {
          console.log(res)
          if (res.status) {
            this.$msgBox.show('组织单元删除成功！')
            this.deleteOrganizationUnitSelect = ''
            this.deleteOrganizationUnitShow = false
            this.refresh()
          } else {
            this.$msgBox.error(res.message)
          }
        })
        .catch(err => {
          console.log(err)
          this.$msgBox.error('组织单元删除失败！')
        })
    },
    opendeleteOrganizationUnit(item) {
      console.log(item)
      this.deleteOrgGroup({
        backup: false,
        ids: [item.phid]
      }).catch(err => {
        this.$msgBox(err.message || '删除失败')
      })
    },
    deleteOrgUnitAfterSelect() {
      if (this.deleteOrganizationUnitSelect === '') {
        this.$msgBox.error('请选择删除方式！')
        return
      }
      this.deleteOrgGroup({
        backup: !!this.deleteOrganizationUnitSelect,
        ids: [this.deleteOrganizationUnitItem.phid]
      })
    },
    checkTreeChange(item, newVal, sonVal) {
      var phidlist = []
      function getPhid(list) {
        list.forEach(item => {
          phidlist.push(item.phid)
          if (item.children && item.children.length) {
            getPhid(item.children)
          }
        })
      }
      if (item.children && item.children.length) {
        getPhid(item.children)
        var arr = this.$refs.orgTree.getCheckedKeys()
        if (newVal) {
          this.$refs.orgTree.setCheckedKeys(
            [...new Set(arr.concat(phidlist))],
            true
          )
        } else {
          this.$refs.orgTree.setCheckedKeys(
            arr.filter(i => !phidlist.includes(i)),
            false
          )
        }
      }
    },
    // 组织单元-快捷删除所属组织并保存
    fastSave() {
      const ids = this.$refs.editOrgTree.deleteIds
      this.deleteOrgGroup({
        ids
      }).finally(() => {
        this.editOrganizationUnitShow = false
      })
    },
    // 刷新
    refresh() {
      this.getOrgList()
      this.getCodeLengthSettingList()
      this.getOrgGroupByParentId(0).then(res => {
        this.unitTableData = res
      })
      this.orgGroupKey = Math.random()
    },
    handleExport() {
      // const param = {
      //   nameOrEncode: this.getDataParams.nameOrEncode,
      //   orgGroupId: this.getDataParams.orgGroupId,
      //   tradeType: this.getDataParams.tradeType
      // }
      // window.open('/setting/organization/export')
      orgExport({
        nameOrEncode: this.getDataParams.nameOrEncode,
        orgGroupId: this.getDataParams.orgGroupId,
        tradeType: this.getDataParams.tradeType
      })
    }
  }
}
</script>

<style lang="scss">
@import "../../styles/variables.scss";
.organizationBody {
  height: 100%;
  // min-width: 1390px;
  min-width: 1270px;
  padding: 20px;
  // overflow: hidden;
  .topHandleCon {
    .topHandleConLeft {
      .checkbox {
        height: 33px;
        line-height: 33px;
      }

      .time-title {
        width: 100%;
        margin-top: 7px;
        text-align: center;
        border-right: 1px solid #cccccc;
      }
    }
  }
  .organizationBody-main {
    /*width:calc(100% - 35px);*/
    /*height: 900px;*/
    height: 100%;
    width: 100%;
    background-color: #ffffff;
    display: inline-block;
    ul.organizationBody-nav {
      > li {
        padding: 13px;
        padding-left: 51px;
        cursor: pointer;
        &::before {
          content: "";
          display: inline-block;
          border-radius: 50%;
          background: #b7b7b7;
          width: 10px;
          height: 10px;
          margin-right: 10px;
        }
        &:first-of-type.active {
          background-image: url("../../assets/images/organization/tab1.png");
          position: relative;
          overflow: visible;
          background-size: 100% 55px;
          background-position: 11px -4px;
          background-repeat: no-repeat;
          z-index: 18;
          &::before {
            background: #87ba29;
          }
        }
        &:not(:first-of-type).active {
          background-image: url("../../assets/images/organization/tab2.png");
          position: relative;
          overflow: visible;
          background-size: 100% 55px;
          background-position: 11px -5px;
          background-repeat: no-repeat;
          z-index: 18;
          &::before {
            background: #87ba29;
          }
        }
      }
    }
    .link {
      color: $btn-blue;
      text-decoration: underline;
      cursor: pointer;
    }
  }
  .pageArea {
    float: right;
    margin: 10px;
  }

  .el-radio.is-bordered {
    padding-left: 0;
    padding-right: 0;
    border-color: transparent;
  }
  .el-radio.is-bordered.is-checked {
    border-color: transparent;
  }
  .el-radio {
    margin-right: 0px;
  }
  // 去掉table外边框
  .el-table--border {
    border: 0;
  }
  // 右边框
  .el-table--group::after,
  .el-table--border::after {
    width: 0;
  }
  .el-table__row td:last-of-type {
    border-right: 0;
  }
  thead th:nth-last-child(2) {
    border-right: 0;
  }
  // 树
  .el-tree {
    height: 100%;
    overflow: auto;
  }
  .el-tree-node__content {
    height: 44px;
  }

  // dialog
  .addRegistClass {
    width: 845px;
    border-radius: 8px;
    overflow: hidden;
    .el-dialog__header {
      background: $blue;
      .el-dialog__headerbtn {
        top: 12px;
      }
      .el-dialog__headerbtn .el-dialog__close,
      .el-dialog__title {
        color: #fff;
      }
      .el-dialog__headerbtn .el-dialog__close {
        font-size: 0.22rem;
      }
    }
    .el-dialog__body {
      padding: 0;
    }
  }
}
.txtR {
  text-align: right;
}
.fresh {
  // width: 40px;
  border-radius: 5px;
  text-align: center;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  > div {
    font-size: 23px;
    color: #777;
    line-height: 30px;
    display: inline-block;
    cursor: pointer;
    img {
      vertical-align: middle;
      height: 22px;
      margin-top: -5px;
    }
  }
}
.addDialog-title {
  color: rgb(66, 168, 253);
  font-size: 0.18rem;
  width: 100%;
  border-bottom: 2px solid rgb(66, 168, 253);
}
.editOrganizationClass {
  width: auto;
  min-width: 500px;
  border-radius: 8px;
  overflow: hidden;
  .el-dialog__header {
    background: $blue;
    padding: 10px;
    .el-dialog__headerbtn {
      top: 12px;
    }
    .el-dialog__headerbtn .el-dialog__close,
    .el-dialog__title {
      color: #fff;
    }
    .el-dialog__headerbtn .el-dialog__close {
      font-size: 0.22rem;
    }
  }
  .el-dialog__body {
    padding: 10px;
  }
}
.addOrganizationClass {
  width: 1000px;
  border-radius: 8px;
  overflow: hidden;
  .el-dialog__header {
    background: $blue;
    padding: 10px;
    .el-dialog__headerbtn {
      top: 12px;
    }
    .el-dialog__headerbtn .el-dialog__close,
    .el-dialog__title {
      color: #fff;
    }
    .el-dialog__headerbtn .el-dialog__close {
      font-size: 0.22rem;
    }
  }
  .el-dialog__body {
    padding: 0;
  }
}
.deleteOrganizationClass {
  width: 400px;
  border-radius: 8px;
  overflow: hidden;
  .el-dialog__header {
    background: $blue;
    padding: 10px;
    .el-dialog__headerbtn {
      top: 12px;
    }
    .el-dialog__headerbtn .el-dialog__close,
    .el-dialog__title {
      color: #fff;
    }
    .el-dialog__headerbtn .el-dialog__close {
      font-size: 0.22rem;
    }
  }
  .el-dialog__body {
    padding: 10px 0;
  }
  .el-radio-group {
    .el-radio {
      margin-left: 70px;
      line-height: 40px;
    }
  }
  .radio-label {
    font-size: 14px;
    display: inline-block;
    margin-left: 94px;
    color: #b3b1b1;
  }
}
.createUnitClass {
  width: 500px;
  border-radius: 8px;
  overflow: hidden;
  .el-dialog__header {
    background: $blue;
    padding: 10px;
    .el-dialog__headerbtn {
      top: 12px;
    }
    .el-dialog__headerbtn .el-dialog__close,
    .el-dialog__title {
      color: #fff;
    }
    .el-dialog__headerbtn .el-dialog__close {
      font-size: 0.22rem;
    }
  }
  .el-dialog__body {
    padding: 20px;
  }
  .el-radio-group {
    margin: 10px 0;
    .el-radio {
      padding: 0 65px;
      line-height: 30px;
    }
  }
  .createUnitList {
    padding-left: 110px;
    margin-bottom: 10px;
    > span {
      display: inline-block;
      margin-left: -110px;
      width: 105px;
    }
    > div.el-textarea {
      vertical-align: top;
    }
  }
}
.storkZGLHClass {
  width: 1250px;
  .el-dialog__header {
    background: #fff;
    padding: 10px;
    .el-dialog__headerbtn .el-dialog__close,
    .el-dialog__title {
      color: $light-blue;
    }
  }
}
.moreBtn {
  /*padding: 10px;*/
  > li {
    margin-bottom: 10px;
    &:last-of-type {
      margin-bottom: 0px;
    }
    > span {
      display: inline-block;
      width: 100%;
      margin: 0;
    }
  }
}
.greenBtnW {
  .greenBtn {
    min-width: 100%;
    margin: 0;
  }
}
.highSearch {
  width: 350px;
  ul {
    > li {
      margin-bottom: 10px;
      > div {
        display: inline-block;
        width: 70px;
        &:last-of-type {
          width: 260px;
        }
      }
    }
  }
  .handleBtn {
    text-align: center;
    > span {
      display: inline-block;
      width: 60px;
      &:last-of-type {
        margin-left: 40px;
      }
    }
  }
}
ul.unitEdit {
  text-align: center;
  > li {
    line-height: 25px;
    cursor: pointer;
  }
}
</style>
<style scoped>
.company-sel >>> .el-input__inner {
  border: none;
}
.organizationBody >>> .el-range-editor.el-input__inner {
  width: 300px;
  border: 0;
}
.organizationBody >>> .el-range-editor--small .el-range-separator {
  padding: 0;
}

.organizationBody >>> .el-range-editor--small .el-range-input {
  width: 100px;
}
</style>
